<script setup lang="ts">
import { onMounted, ref } from 'vue';
// 移除未使用的Ref类型
import { NAvatar, NButton, NCard, NDivider, NEmpty, NInput, NSpace } from 'naive-ui';
import {
  acceptFriendRequest,
  addFriendReal,
  getFriendRequestList,
  rejectFriendRequest,
  searchFriendApi,
  searchFriendWithGamesApi
} from '@/service/api/friend';
import { useAuthStore } from '@/store/modules/auth';
import emitter from '@/utils/event-bus';
import SvgIcon from '@/components/custom/svg-icon.vue';
interface UserInfo {
  id: number;
  username: string;
  email: string;
  phoneNumber: string;
  gender: string;
  avatar: string;
  createTime: string;
}
interface UserWithGames {
  userInfo: UserInfo;
  gameList: any[];
  gameCount: number;
  totalPlayTime: number;
  recentGames: any[];
}

const keyword = ref('');
const userWithGames = ref<UserWithGames | null>(null);
const errorMsg = ref<string>('');

// 移除未使用的testUsers

// 测试数据：收到的好友申请
const receivedRequests = ref<any[]>([]);

const requestLoading = ref(false);
const acceptLoading = ref(false);

// 新增：标记当前右侧详情是申请人卡片还是搜索用户
const detailType = ref<'search' | 'request' | null>(null);

async function handleSearch() {
  errorMsg.value = '';
  userWithGames.value = null;
  if (!keyword.value) {
    errorMsg.value = '请输入用户名或手机号';
    return;
  }
  try {
    const res = await searchFriendWithGamesApi(keyword.value);
    console.log('API响应:', res);
    const data = res && res.data ? res.data : null;
    if (data && data.userInfo) {
      userWithGames.value = data;
      errorMsg.value = '';
      detailType.value = 'search';
    } else {
      errorMsg.value = '未找到用户';
      userWithGames.value = null;
      detailType.value = null;
    }
  } catch (error) {
    console.error('搜索好友错误:', error);
    errorMsg.value = '网络错误，请稍后重试';
    userWithGames.value = null;
    detailType.value = null;
  }
}

async function handleAddFriend(user: any) {
  requestLoading.value = true;
  try {
    const authStore = useAuthStore();
    const userId = Number(authStore.userInfo.userId);
    if (!userId) {
      window.$message?.error('请先登录');
      return;
    }
    const friendId = user.id; // 取userWithGames.userInfo.id
    const tag = '朋友';
    const res = await addFriendReal({ userId, friendId, tag });
    let code = -1;
    let message = '';
    if (res && res.response && res.response.data) {
      code = (res.response.data as any).code;
      message = (res.response.data as any).message;
    }
    if (code === 200) {
      window.$message?.success('添加好友申请已发送');
    } else {
      window.$message?.error(message || '添加失败');
    }
  } catch (e: any) {
    window.$message?.error(e?.message || '网络错误，添加失败');
  } finally {
    requestLoading.value = false;
  }
}

// 修改handleAcceptRequest，调用acceptFriendRequest接口
async function handleAcceptRequest(user: any) {
  acceptLoading.value = true;
  try {
    const authStore = useAuthStore();
    const userId = Number(authStore.userInfo.userId); // 被申请人ID
    const friendId = user.id || user.friendId; // 申请人ID
    const res = await acceptFriendRequest({ userId, friendId });
    let code = -1;
    let message = '';
    if (res && res.response && res.response.data) {
      code = (res.response.data as any).code;
      message = (res.response.data as any).message;
    }
    if (code === 200) {
      window.$message?.success('已同意好友申请');
      await loadReceivedRequests();
      userWithGames.value = null;
      detailType.value = null;
      emitter.emit('refresh-friend-list');
    } else {
      window.$message?.error(message || '操作失败');
    }
  } finally {
    acceptLoading.value = false;
  }
}

// 新增：左侧列表专用同意方法
async function handleAcceptRequestFromList(user: any) {
  acceptLoading.value = true;
  try {
    const authStore = useAuthStore();
    const userId = Number(authStore.userInfo.userId); // 被申请人ID
    const friendId = user.userId; // 申请人ID，修正为user.userId
    const res = await acceptFriendRequest({ userId, friendId });
    let code = -1;
    let message = '';
    if (res && res.response && res.response.data) {
      code = (res.response.data as any).code;
      message = (res.response.data as any).message;
    }
    if (code === 200) {
      window.$message?.success('已同意好友申请');
      await loadReceivedRequests();
      emitter.emit('refresh-friend-list');
      // 不影响右侧详情
    } else {
      window.$message?.error(message || '操作失败');
    }
  } finally {
    acceptLoading.value = false;
  }
}

async function loadReceivedRequests() {
  const authStore = useAuthStore();
  const userId = Number(authStore.userInfo.userId);
  if (!userId) return;
  try {
    const res = await getFriendRequestList(userId);
    if (res && res.response && res.response.data && Array.isArray(res.response.data.data)) {
      receivedRequests.value = res.response.data.data;
    } else {
      receivedRequests.value = [];
    }
  } catch {
    receivedRequests.value = [];
  }
}
onMounted(loadReceivedRequests);

// 性别英文转中文
function getGenderLabel(gender: string) {
  if (gender === 'Male') return '男';
  if (gender === 'Female') return '女';
  return gender;
}

// 新增：点击申请人卡片时，调用搜索好友API获取详细信息
async function handleRequestCardClick(user: any) {
  try {
    const res = await searchFriendApi(user.friendUsername);
    // 兼容后端返回格式
    let userInfo = null;
    if (res && res.response && res.response.data && res.response.data.data) {
      // 假设data为数组，取第一个
      const arr = Array.isArray(res.response.data.data) ? res.response.data.data : [res.response.data.data];
      userInfo = arr[0];
    }
    if (userInfo) {
      userWithGames.value = {
        userInfo: {
          id: userInfo.id,
          username: userInfo.username,
          email: userInfo.email,
          phoneNumber: userInfo.phoneNumber || '',
          gender: userInfo.gender || '',
          avatar: userInfo.avatar,
          createTime: userInfo.createTime || ''
        },
        gameList: [],
        gameCount: 0,
        totalPlayTime: 0,
        recentGames: []
      };
      detailType.value = 'request';
    } else {
      window.$message?.error('未查到详细信息');
    }
  } catch {
    window.$message?.error('获取详情失败');
  }
}

// 修改handleRejectRequest，调用rejectFriendRequest接口
async function handleRejectRequest(user: any) {
  requestLoading.value = true;
  try {
    const authStore = useAuthStore();
    const userId = Number(authStore.userInfo.userId); // 被申请人ID
    const friendId = user.id || user.friendId; // 申请人ID
    const res = await rejectFriendRequest({ userId, friendId });
    let code = -1;
    let message = '';
    if (res && res.response && res.response.data) {
      code = (res.response.data as any).code;
      message = (res.response.data as any).message;
    }
    if (code === 200) {
      window.$message?.success('已拒绝好友申请');
      await loadReceivedRequests();
      userWithGames.value = null;
      detailType.value = null;
    } else {
      window.$message?.error(message || '操作失败');
    }
  } finally {
    requestLoading.value = false;
  }
}
</script>

<template>
  <div class="friends-page">
    <!-- 左侧栏 -->
    <div class="left-panel">
      <!-- 搜索栏 -->
      <NCard
        class="search-card"
        :bordered="false"
        content-style="padding: 20px;"
        style="
          margin-bottom: 20px;
          border-radius: 16px;
          box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
          background: linear-gradient(135deg, #f8fafc 0%, #e0e7ff 100%);
        "
      >
        <div class="search-header">
          <SvgIcon icon="mdi:account-search" style="font-size: 20px; margin-right: 8px; color: var(--primary-color)" />
          <span class="search-title">搜索好友</span>
        </div>
        <NSpace vertical size="large">
          <NInput
            v-model:value="keyword"
            placeholder="输入用户名或手机号"
            clearable
            size="large"
            @keydown.enter="handleSearch"
          >
            <template #suffix>
              <NButton type="primary" size="small" @click="handleSearch">
                <SvgIcon icon="mdi:account-search" style="font-size: 14px" />
              </NButton>
            </template>
          </NInput>
        </NSpace>
        <div v-if="errorMsg && typeof errorMsg === 'string'" class="error" style="color: #e11d48; margin-top: 8px">
          {{ errorMsg }}
        </div>
      </NCard>
      <!-- 收到的好友申请（可选，保留原有结构） -->
      <NCard
        class="request-card"
        :bordered="false"
        content-style="padding: 20px;"
        style="
          border-radius: 16px;
          box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
          background: linear-gradient(135deg, #fefefe 0%, #f1f5f9 100%);
        "
      >
        <div class="request-header">
          <SvgIcon icon="mdi:account-arrow-left" style="font-size: 20px; margin-right: 8px; color: #f59e0b" />
          <span class="request-title">收到的好友申请</span>
        </div>
        <div class="request-list">
          <div v-if="receivedRequests.length === 0" style="color: #aaa; text-align: center">暂无好友申请</div>
          <div
            v-for="user in receivedRequests"
            :key="user.id"
            class="request-item"
            @click="handleRequestCardClick(user)"
          >
            <NAvatar
              :src="user.friendAvatar"
              :fallback-src="`https://api.dicebear.com/7.x/avataaars/svg?seed=${user.friendUsername}`"
              size="medium"
              round
            />
            <div class="request-info">
              <div class="request-name">{{ user.friendUsername }}</div>
              <div v-if="user.friendEmail" class="request-email">{{ user.friendEmail }}</div>
              <div class="request-time">{{ user.createTime }}</div>
            </div>
            <NButton
              type="primary"
              size="small"
              :loading="acceptLoading"
              @click.stop="handleAcceptRequestFromList(user)"
            >
              同意
            </NButton>
          </div>
        </div>
      </NCard>
    </div>
    <!-- 右侧栏 -->
    <div class="right-panel">
      <!-- 用户详细信息及游戏信息 -->
      <NCard
        v-if="userWithGames"
        class="detail-card"
        :bordered="false"
        content-style="padding: 24px;"
        style="
          border-radius: 16px;
          box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
          background: linear-gradient(135deg, #fefefe 0%, #f8fafc 100%);
        "
      >
        <div class="detail-header">
          <div class="detail-avatar-section">
            <NAvatar
              :src="userWithGames.userInfo.avatar"
              :fallback-src="`https://api.dicebear.com/7.x/avataaars/svg?seed=${userWithGames.userInfo.username}`"
              size="large"
              round
            />
            <div class="detail-basic-info">
              <h3 class="detail-name">{{ userWithGames.userInfo.username }}</h3>
              <div class="detail-email">{{ userWithGames.userInfo.email }}</div>
              <div class="detail-gender">性别：{{ getGenderLabel(userWithGames.userInfo.gender) }}</div>
            </div>
          </div>
        </div>
        <NDivider />
        <div class="detail-content">
          <div class="info-cards">
            <div class="info-card">
              <SvgIcon icon="mdi:cellphone" style="font-size: 22px; color: #0ea5e9; margin-right: 10px" />
              <div class="info-card-content">
                <div class="info-card-label">手机号</div>
                <div class="info-card-value">{{ userWithGames.userInfo.phoneNumber }}</div>
              </div>
            </div>
            <div class="info-card">
              <SvgIcon icon="mdi:calendar-check" style="font-size: 22px; color: #f59e42; margin-right: 10px" />
              <div class="info-card-content">
                <div class="info-card-label">注册时间</div>
                <div class="info-card-value">{{ userWithGames.userInfo.createTime }}</div>
              </div>
            </div>
          </div>
          <!-- 添加好友按钮/同意/拒绝 -->
          <div class="add-friend-section">
            <template v-if="detailType === 'search'">
              <NButton
                type="primary"
                size="large"
                :loading="requestLoading"
                style="width: 100%; margin-top: 16px"
                @click="handleAddFriend(userWithGames.userInfo)"
              >
                <SvgIcon icon="mdi:account-plus" style="font-size: 16px; margin-right: 8px" />
                添加好友
              </NButton>
            </template>
            <template v-else-if="detailType === 'request'">
              <NButton
                type="primary"
                size="large"
                style="width: 48%; margin-top: 16px; margin-right: 4%"
                :loading="acceptLoading"
                @click="handleAcceptRequest(userWithGames.userInfo)"
              >
                <SvgIcon icon="mdi:check" style="font-size: 16px; margin-right: 8px" />
                同意
              </NButton>
              <NButton
                type="error"
                size="large"
                style="width: 48%; margin-top: 16px"
                :loading="acceptLoading"
                @click="handleRejectRequest(userWithGames.userInfo)"
              >
                <SvgIcon icon="mdi:close" style="font-size: 16px; margin-right: 8px" />
                拒绝
              </NButton>
            </template>
          </div>
          <!-- 游戏信息区块 -->
          <div class="games-section">
            <div class="games-title" style="margin-top: 24px">
              <SvgIcon icon="mdi:gamepad-variant" style="font-size: 20px; margin-right: 8px" />
              <span>游戏统计</span>
            </div>
            <div>游戏总数：{{ userWithGames.gameCount }}</div>
            <div>总游戏时长：{{ userWithGames.totalPlayTime }} 分钟</div>
            <div class="games-title" style="margin-top: 12px">
              <SvgIcon icon="mdi:history" style="font-size: 20px; margin-right: 8px" />
              <span>最近游玩</span>
            </div>
            <div v-if="userWithGames.recentGames && userWithGames.recentGames.length">
              <div
                v-for="game in userWithGames.recentGames"
                :key="game.id"
                class="game-card"
                style="display: flex; align-items: center; margin-bottom: 8px"
              >
                <img
                  :src="game.pic || game.gameImageUrl"
                  style="width: 40px; height: 40px; margin-right: 8px; border-radius: 6px; object-fit: cover"
                />
                <span>{{ game.gameName }}</span>
                <span style="margin-left: 8px; color: #888; font-size: 12px">{{ game.playTime }} 分钟</span>
              </div>
            </div>
            <div v-else style="color: #aaa; margin-bottom: 8px">暂无最近游玩记录</div>
            <div class="games-title" style="margin-top: 12px">
              <SvgIcon icon="mdi:view-grid" style="font-size: 20px; margin-right: 8px" />
              <span>游戏库</span>
            </div>
            <div v-if="userWithGames.gameList && userWithGames.gameList.length">
              <div
                v-for="game in userWithGames.gameList"
                :key="game.id"
                class="game-card"
                style="display: flex; align-items: center; margin-bottom: 8px"
              >
                <img
                  :src="game.pic || game.gameImageUrl"
                  style="width: 40px; height: 40px; margin-right: 8px; border-radius: 6px; object-fit: cover"
                />
                <span>{{ game.gameName }}</span>
                <span style="margin-left: 8px; color: #888; font-size: 12px">{{ game.playTime }} 分钟</span>
              </div>
            </div>
            <div v-else style="color: #aaa">暂无游戏</div>
          </div>
        </div>
      </NCard>
      <!-- 空状态 -->
      <NCard
        v-else-if="keyword && !userWithGames"
        class="empty-card"
        :bordered="false"
        content-style="padding: 40px 20px; text-align: center;"
        style="border-radius: 16px; box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08)"
      >
        <NEmpty description="未找到相关好友">
          <template #icon>
            <SvgIcon name="activity" style="font-size: 48px; color: #cbd5e1" />
          </template>
        </NEmpty>
      </NCard>
      <!-- 默认提示 -->
      <NCard
        v-else
        class="default-card"
        :bordered="false"
        content-style="padding: 40px 20px; text-align: center;"
        style="
          border-radius: 16px;
          box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
          background: linear-gradient(135deg, #fefefe 0%, #f8fafc 100%);
        "
      >
        <SvgIcon icon="mdi:account-group" style="font-size: 48px; color: #6366f1; margin-bottom: 16px" />
        <h3 style="color: #64748b; margin-bottom: 8px">欢迎来到好友管理</h3>
        <p style="color: #94a3b8">在左侧搜索好友，右侧显示详细信息</p>
      </NCard>
    </div>
  </div>
</template>

<style scoped>
.friends-page {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 24px;
  padding: 24px;
  min-height: calc(100vh - 120px);
}
.left-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.right-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.search-header,
.request-header,
.results-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.search-title,
.request-title,
.results-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.request-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.request-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 12px;
  background: white;
  border: 1px solid #e2e8f0;
}

.request-info {
  flex: 1;
}

.request-name {
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 2px;
}

.request-phone {
  font-size: 12px;
  color: #64748b;
}

.request-time {
  font-size: 12px;
  color: #94a3b8;
}

.search-results {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.result-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 12px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #e2e8f0;
}

.result-item:hover,
.result-item.active {
  border-color: var(--primary-color, #6366f1);
  background: #f8fafc;
}

.result-info {
  flex: 1;
}

.result-name {
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 2px;
}

.result-email {
  font-size: 12px;
  color: #64748b;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.detail-avatar-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.detail-basic-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-name {
  font-size: 24px;
  font-weight: 700;
  color: #1e293b;
  margin: 0;
}

.detail-email {
  color: #64748b;
  font-size: 14px;
}

.detail-gender {
  color: #64748b;
  font-size: 14px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-label {
  font-weight: 600;
  color: #475569;
  min-width: 80px;
}

.detail-value {
  color: #1e293b;
}

.detail-section {
  margin-top: 20px;
}

.info-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.info-card {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 16px;
  border-radius: 12px;
  background: #f0f9eb;
  border: 1px solid #d1fae5;
}

.info-card-content {
  display: flex;
  flex-direction: column;
}

.info-card-label {
  font-size: 12px;
  color: #34d399;
}

.info-card-value {
  font-size: 16px;
  font-weight: 600;
  color: #06b6d4;
}

.games-section {
  margin-top: 20px;
  margin-bottom: 20px;
}

.games-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #4f46e5;
  margin-bottom: 12px;
}

.games-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
}

.game-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
  border-radius: 12px;
  background: #f3f4f6;
  border: 1px solid #e5e7eb;
  cursor: pointer;
  transition: all 0.2s;
}

.game-card:hover {
  background: #e5e7eb;
  border-color: #d1d5db;
}

.game-cover {
  width: 100%;
  height: 60px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 8px;
}

.game-info {
  text-align: center;
  width: 100%;
}

.game-name {
  font-size: 12px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.game-hours {
  font-size: 10px;
  color: #4b5563;
  margin-bottom: 2px;
}

.game-type {
  font-size: 10px;
  color: #6b7280;
  margin-bottom: 2px;
}

.game-last {
  font-size: 9px;
  color: #9ca3af;
}

.no-games {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  background: #f8fafc;
  border: 1px dashed #cbd5e1;
}

.empty-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
  background: linear-gradient(135deg, #fefefe 0%, #f8fafc 100%);
}

@media (max-width: 768px) {
  .friends-page {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 16px;
  }
}
</style>
